"""
AI分类器基类

定义AI分类器的通用接口和数据结构。
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, field
from datetime import datetime
import json

from src.modules.scanners.base import FileInfo, FileCategory


@dataclass
class ClassificationResult:
    """AI分类结果"""
    
    # 分类信息
    category: FileCategory = FileCategory.UNCLASSIFIED
    confidence: float = 0.0
    reasoning: str = ""
    features: List[str] = field(default_factory=list)
    
    # 元信息
    classifier_type: str = "ai"
    model_name: str = ""
    processing_time: float = 0.0
    timestamp: Optional[datetime] = None
    
    # 原始数据
    raw_response: str = ""
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    # 错误信息
    success: bool = True
    error: str = ""
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = {}
        for key, value in self.__dict__.items():
            if isinstance(value, FileCategory):
                result[key] = value.value
            elif isinstance(value, datetime):
                result[key] = value.isoformat() if value else None
            else:
                result[key] = value
        return result
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'ClassificationResult':
        """从字典创建"""
        # 处理枚举字段
        if 'category' in data and isinstance(data['category'], str):
            data['category'] = FileCategory(data['category'])
        
        # 处理datetime字段
        if 'timestamp' in data and data['timestamp']:
            if isinstance(data['timestamp'], str):
                data['timestamp'] = datetime.fromisoformat(data['timestamp'])
        
        return cls(**data)
    
    def to_json(self) -> str:
        """转换为JSON字符串"""
        return json.dumps(self.to_dict(), indent=2, ensure_ascii=False, default=str)


class AIClassifier(ABC):
    """
    AI分类器抽象基类
    
    定义AI分类器的标准接口。
    """
    
    @property
    @abstractmethod
    def name(self) -> str:
        """分类器名称"""
        pass
    
    @property
    @abstractmethod
    def version(self) -> str:
        """分类器版本"""
        pass
    
    @property
    @abstractmethod
    def supported_file_types(self) -> List[str]:
        """支持的文件类型"""
        pass
    
    @abstractmethod
    async def classify(self, file_info: FileInfo, **kwargs) -> ClassificationResult:
        """
        分类文件
        
        Args:
            file_info: 文件信息
            **kwargs: 其他参数
        
        Returns:
            分类结果
        """
        pass
    
    @abstractmethod
    def is_available(self) -> bool:
        """检查分类器是否可用"""
        pass
    
    def supports_file_type(self, file_type: str) -> bool:
        """检查是否支持指定的文件类型"""
        return file_type.lower() in [ft.lower() for ft in self.supported_file_types]
    
    async def batch_classify(self, file_infos: List[FileInfo], **kwargs) -> List[ClassificationResult]:
        """
        批量分类文件
        
        Args:
            file_infos: 文件信息列表
            **kwargs: 其他参数
        
        Returns:
            分类结果列表
        """
        results = []
        
        for file_info in file_infos:
            try:
                result = await self.classify(file_info, **kwargs)
                results.append(result)
            except Exception as e:
                # 创建错误结果
                error_result = ClassificationResult(
                    success=False,
                    error=str(e),
                    classifier_type=self.name,
                    timestamp=datetime.now()
                )
                results.append(error_result)
        
        return results
    
    def get_metadata(self) -> Dict[str, Any]:
        """获取分类器元数据"""
        return {
            "name": self.name,
            "version": self.version,
            "supported_file_types": self.supported_file_types,
            "is_available": self.is_available()
        }


class ClassifierRegistry:
    """分类器注册表"""
    
    def __init__(self):
        self._classifiers: Dict[str, AIClassifier] = {}
    
    def register(self, name: str, classifier: AIClassifier) -> None:
        """注册分类器"""
        self._classifiers[name] = classifier
    
    def unregister(self, name: str) -> None:
        """注销分类器"""
        if name in self._classifiers:
            del self._classifiers[name]
    
    def get(self, name: str) -> Optional[AIClassifier]:
        """获取分类器"""
        return self._classifiers.get(name)
    
    def list_classifiers(self) -> List[str]:
        """列出所有注册的分类器"""
        return list(self._classifiers.keys())
    
    def get_available_classifiers(self) -> List[str]:
        """获取可用的分类器"""
        return [
            name for name, classifier in self._classifiers.items()
            if classifier.is_available()
        ]
    
    def get_classifiers_for_file_type(self, file_type: str) -> List[str]:
        """获取支持指定文件类型的分类器"""
        return [
            name for name, classifier in self._classifiers.items()
            if classifier.supports_file_type(file_type) and classifier.is_available()
        ]


# 全局分类器注册表
classifier_registry = ClassifierRegistry()
